package com.zb.controller;

import com.alibaba.fastjson.JSONObject;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.http.URIUtil;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpException;
import org.apache.http.client.fluent.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhanghua on 2017/3/23 0023.
 */
@Controller
@RequestMapping("/pay")
public class PayController
{
    private Logger logger = LoggerFactory.getLogger(PayController.class);

    String ARG_DELIMITER = "___";

    @Value("${atomu.server.url}")
    private String serverUrl;

    /**
     * 微信获取openId时时，构建请求地址oauth2请求地址
     *
     * @return
     */
    @RequestMapping("/wecahtOauth2buildAuthorizationUrl")
    @ResponseBody
    public String wecahtOauth2buildAuthorizationUrl(@RequestParam String redirectUrl )
    {

        String arg = serverUrl + "/pay/oauth2getAccessToken?arg=" + "----"
                + ARG_DELIMITER + redirectUrl;

        String oauth2Url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + "appid" + "&redirect_uri=" + arg
                + "&response_type=code&scope=snsapi_base&state=" + arg + "#wechat_redirect";
        logger.info("oauth2Url:{}", oauth2Url);

        return oauth2Url;
    }

    @RequestMapping(value = "/oauth2getAccessToken")
    public void oauth2getAccessToken(String code, String scope, String state, String arg, HttpServletResponse response)
            throws IOException, WxErrorException, HttpException
    {

        String argArr[] = org.apache.commons.lang3.StringUtils.split(arg, ARG_DELIMITER, 2);
        String appId = argArr[0];
        String redirectUrl = argArr[1];

        logger.info("request in .. code : {}, scope : {},state : {},args: {},appId:{},redirectUrl:{}", code, scope, state,
                arg, appId, redirectUrl);
        if (StringUtils.isEmpty(code))
        {
            scope = WxConsts.OAUTH2_SCOPE_BASE;
            String redirectURI = state;
            String authUrl = oauth2buildAuthorizationUrl(redirectURI, scope, state);
            logger.info("authUrl-->{}", authUrl);
            response.sendRedirect(authUrl);
        } else
        {

//            WxMpService wxMpService = new WxMpServiceImpl();

            WxMpOAuth2AccessToken accessToken = oauth2getAccessToken(code);
            JSONObject json = new JSONObject();
            json.put("openId", accessToken.getOpenId());
            logger.debug("openId：{}", accessToken.getOpenId());

            logger.info("redirectUrl:[{}]", redirectUrl);
            response.sendRedirect(redirectUrl + "?openId=" + accessToken.getOpenId());
        }
    }

    private WxMpOAuth2AccessToken oauth2getAccessToken(String code) throws WxErrorException
    {
        StringBuilder url = new StringBuilder();
        url.append("https://api.weixin.qq.com/sns/oauth2/access_token?");
        url.append("appid=").append("");
        url.append("&secret=").append("");
        url.append("&code=").append(code);
        url.append("&grant_type=authorization_code");

        return this.getOAuth2AccessToken(url);
    }

    @RequestMapping(value = "/getUserAgent")
    @ResponseBody
    public Map<String, String> getUserAgent(HttpServletRequest request)
    {
        Map<String, String> map = new HashMap<>();
        String userAgent = request.getHeader("User-Agent");
        String agent = userAgent.toLowerCase();
        if (agent.indexOf("micromessenger") > 0)
        {
            logger.info("wx");
            map.put("userAgent", "1");
        } else if (agent.indexOf("alipayclient") > 0)
        {
            map.put("userAgent", "2");
        } else
        {
            map.put("userAgent", "3");
        }
        return map;
    }

    private WxMpOAuth2AccessToken getOAuth2AccessToken(StringBuilder url) throws WxErrorException
    {
        try
        {
//            RequestExecutor<String, String> executor = new SimpleGetRequestExecutor();
//            String responseText = executor.execute(this.getHttpclient(), this.httpProxy, url.toString(), null);
                String responseText = Request.Get(url.toString()).execute().returnContent().asString();
            return WxMpOAuth2AccessToken.fromJson(responseText);
        } catch (IOException e)
        {
            throw new RuntimeException(e);
        }
    }

    private String oauth2buildAuthorizationUrl(String redirectURI, String scope, String state)
    {
        StringBuilder url = new StringBuilder();
        url.append("https://open.weixin.qq.com/connect/oauth2/authorize?");
        url.append("appid=").append("");
        url.append("&redirect_uri=").append(URIUtil.encodeURIComponent(redirectURI));
        url.append("&response_type=code");
        url.append("&scope=").append(scope);
        if (state != null)
        {
            url.append("&state=").append(state);
        }
        url.append("#wechat_redirect");
        return url.toString();
    }

}
